/*
 * Copyright (c) 2019 DawnFramework. All Rights Reserved.
 * Licensed under the MIT (LICENSE) license.
 */

package org.dawn.common.apiclient.except;

import org.dawn.common.core.except.IError;

import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

/**
 * 自定义错误枚举，注意httpStatusCode与errorCode一一对应
 *
 * @author: Gang.Dong on 2019-04-26
 */
public enum BaseErrors implements IError<Integer> {

    BAD_REQUEST(400, "请求错误"),
    UNAUTHORIZED(401, "认证失败"),
    FORBIDDEN(403, "不允许的请求"),
    NOT_FOUND(404, "无法访问资源"),
    METHOD_NOT_ALLOWED(405, "不支持的请求方法"),
    CONFLICT(409, "一个冲突资源已存在"),
    REQUEST_WAS_DENIED(412, "请求被拒绝"),
    UNPROCESSABLE(422, "无法处理的实体"),
    INTERNAL_SERVER_ERROR(500, "服务器内部错误"),
    ;

    private final Integer statusCode;
    private final String message;

    BaseErrors(Integer statusCode, String message) {
        this.statusCode = statusCode;
        this.message = message;
    }

    public static BaseErrors find(final Integer statusCode) {
        // 找不对应的httpStatusCode默认返回500
        Optional<BaseErrors> found = Arrays.stream(BaseErrors.values())
                .filter(it -> Objects.equals(it.statusCode, statusCode))
                .findFirst();
        return found.orElse(BaseErrors.INTERNAL_SERVER_ERROR);
    }


    @Override
    public Integer errcode() {
        return statusCode;
    }

    @Override
    public String errmsg() {
        return message;
    }
}
